require('./page.css');
let cp = require('cp');

var vm_password = avalon.define({
  $id: 'mc_password',
  next_toggle: 1,
  mobile: '',
  getCodeText: '点击获取',
  disableClass: '',
  time: '',
  code: '',
  password: '',
  new_password_2: '',
  token: '',
  validate: {
    onValidateAll: function(reasons) {
      if (reasons.length) {
        cp.layerMsg({
          msg: reasons[0].getMessage(),
        });
      } else {
        vm_password.next_toggle = 2;
      }
    },
  },
  validate_password: {
    onValidateAll: function(reasons) {
      if (reasons.length) {
        cp.layerMsg({
          msg: reasons[0].getMessage(),
        });
      } else {
        let md5 = require('js-md5');
        let Base64 = require('js-base64').Base64;
        cp.ajaxUrl({
          cmd: 'com.rel.porg.pb.acc_mobile_repwd_req',
          controller: 'account',
          checkUser: false,
          data: {
            'mobile': vm_password.mobile,
            'vcode': vm_password.code,
            'passwd': Base64.encode(md5(vm_password.password).toUpperCase()),
          },
          success: function(res) {
            // body...
            vm_password.next_toggle = 3;
            cp.setCookie('token', res.token, 12);
            cp.setCookie('orgid', res.info.orgid, 12);
            setTimeout(() => {
              if (res.token) {
                window.location.href = cp.PAGE_ROOT + 'index/index/page.html';
              }
            }, 3000);
          },
          fail: res => {
            cp.layerMsg({
              msg: res.desc,
            });
          },
        });
      }
    },
  },
  bindGetCode: function(disable) {
    if (disable !== 'disable') {
      if (vm_password.mobile === '') {
        cp.layerMsg({
          msg: '请填写手机号！',
        });
      } else {
        let reg = (/^1[3|4|5|7|8][0-9]{9}$/).test(vm_password.mobile);
        if (reg) {
          cp.ajaxUrl({
            cmd: 'com.rel.porg.pb.acc_send_verfiy_code_req',
            controller: 'account',
            checkUser: false,
            data: {
              mobile: vm_password.mobile,
              module: 2,
            },
            success: function(res) {
              if (res.ret === 1) {
                getTime(120);
              }
            },
            fail: function(res) {
              cp.layerMsg({
                msg: res.desc,
              });
            },
          });
        } else {
          cp.layerMsg({
            msg: '请填写正确的手机号！',
          });
        }
      }
    }
  },
});

function getTime(time) {
  // 倒计时60s
  if (time === 1) {
    vm_password.getCodeText = '点击获取';
    vm_password.disableClass = '';
    vm_password.time = '';
    time = 120;
  } else {
    time--;
    vm_password.time = time;
    setTimeout(function() {
      getTime(time);
    }, 1000);
    vm_password.getCodeText = '重新获取';
    vm_password.disableClass = 'disable';
  }
}
